import { merge } from "./index";

let LOADER_INDEX = 0;
export default options => {
    let opt = {
        url: "",
        proxy: "",
        method: "GET",
        data: {},
        loader: true,
        headers: {},
        before: null,
        after: null,
    };
    opt = merge(true, opt, options);
    opt.method = opt.method.toUpperCase();
    // console.log("requestOptions", opt);
    return new Promise((resolve, reject) => {
        requestHandler(opt)
            .then(_ => {
                const _responseHandler = res => {
                    responseHandler(res, opt)
                        .then(() => {
                            handleAfter(opt, res).then(aRes=>{
                                resolve(aRes);
                            }).catch(aErr=>{
                                reject(aErr);
                            });
                        })
                        .catch(rErr => {
                            handleAfter(opt, rErr)
                                .catch(aErr => {
                                    reject(aErr);
                                });
                        });
                };
                // console.log("--------");
                var opt_url = opt.url.replace('/?', '?');
                opt.url = opt_url;
                console.log("请求地址====="+opt.url);   
                // console.log(opt.headers); 
                // console.log("--------");
                wx.request({
                    method: opt.method,
                    url: opt.url,
                    data: opt.data,
                    timeout: 30000,
                    dataType: "json",
                    header: {
                        ...opt.headers,
                    },
                    success(res) {
                        // console.log("success", res);
                        _responseHandler(res);
                    },
                    fail(res) {
                        // console.log('fail',res);
                        _responseHandler(res);
                    },
                });
            })
            .catch(err => {
                reject(err);
            });
    });
};

const requestHandler = opt => {
    return new Promise((resolve, reject) => {
        if (opt.before) {
            const before = opt.before(opt);
            if (before && before.then) {
                before.then(
                    _ => {
                        resolve({});
                    },
                    error => {
                        reject(error);
                    }
                );
            } else {
                reject({
                    message: "before must be Promise",
                });
            }
        } else {
            resolve({});
        }
    });
};
const responseHandler = (res, opt) => {
    return new Promise((resolve, reject) => {
        if (
            res === void 0 ||
            (res.message && res.message.indexOf("Network") !== -1 && res.message.indexOf("Error") !== -1)
        ) {
            // console.log('服务器地址不存在！');
            res.msgInfo = "服务器地址不存在";
            return reject({
                message: res.msgInfo,
                ...res,
            });
        }
        if (res.statusCode === 200) {
            return resolve(res);
        }
        if (res.errMsg && res.errMsg.indexOf("timeout") !== -1) {
            res.msgInfo = "接口请求超时";
            return reject({
                message: res.msgInfo,
                ...res,
            });
        }
        const _status = res.statusCode;
        switch (_status) {
            case 400:
                res.msgInfo = "错误的请求";
                break;
            case 403:
                res.msgInfo = "拒绝访问";
                break;
            case 404:
                res.msgInfo = `错误的地址: ${opt.url}`;
                break;
            case 401:
                res.msgInfo = `登录过期`;
                break;
            case 408:
                res.msgInfo = "请求超时";
                break;
            case 500:
            case 501:
            case 502:
            case 503:
            case 504:
            case 505:
                res.msgInfo = "服务器错误";
                break;
            default:
                res.msgInfo = "接口请求失败";
                break;
        }
        return reject({
            message: res.msgInfo,
            ...res,
        });
    });
};

const handleAfter = (opt, res) => {
    return new Promise((resolve, reject) => {
        if (opt.after) {
            const after = opt.after(opt, res);
            if (after && after.then) {
                after.then(
                    aRes => {
                        resolve(aRes);
                    },
                    error => {
                        reject(error);
                    }
                );
            } else {
                reject({
                    message: "after must be Promise",
                });
            }
        } else {
           resolve(res);
        }
    });
};
